/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-10
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-23
 * @Description: 
 */
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:image_picker/image_picker.dart';

// 使用示例
//   SquareAvatar(),
//   SquareAvatar(
//     imageUrl:  'images/march.jpg',
//   ),
//   SquareAvatar(
//     imageUrl:
//         '${AppConfig.baseUrl}/cloud/avatars/7238a0b2-215d-4b9a-96e4-0a06aa83a9fd.jpg',
//   ),

class SquareAvatar extends StatelessWidget {
  final double size;
  final double borderRadius;
  final dynamic imageSource;
  final Color? backgroundColor;
  final IconData? icon;
  final Color? iconColor;

  const SquareAvatar({
    super.key,
    this.size = 60.0, // 默认头像大小为60
    this.borderRadius = 10.0, // 默认圆角半径为10
    this.imageSource,
    this.backgroundColor = Colors.white, // 默认背景颜色为白色
    this.iconColor = Colors.black,
    this.icon = Icons.person, // 默认图标为人员图标
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        color: backgroundColor, // 背景颜色
        borderRadius: BorderRadius.circular(borderRadius), // 圆角
      ),
      child: _buildContent(), // 构建图片或图标
    );
  }

  Widget _buildContent() {
    if (imageSource == null) return _buildIcon();

    if (imageSource is String) {
      return _handleStringSource(imageSource as String);
    } else if (imageSource is XFile) {
      return _buildXFileImage(imageSource as XFile);
    }
    return _buildIcon();
  }

  // 图片路径加载
  Widget _handleStringSource(source) {
    // 尝试解析 URL，如果是有效的 URL，加载网络图片
    final uri = Uri.tryParse(source);
    // 网络图片 加载并自动缓存
    if (uri != null && uri.isAbsolute) {
      return CachedNetworkImage(
        imageUrl: source,
        width: size,
        height: size,
        fit: BoxFit.cover,
        // 加载时显示加载指示器
        placeholder: (context, url) => const CircularProgressIndicator(),
        errorWidget: (_, __, ___) => _buildErrorWidget('加载失败'),
      );
    }

    // 本地资源（智能路径处理）
    return _buildLocalImage(source);
  }

  // File文件加载
  Widget _buildXFileImage(source) {
    return Image.file(
      File(source.path),
      width: size,
      height: size,
      fit: BoxFit.cover,
      errorBuilder: (_, __, ___) => _buildErrorWidget('资源未找到'),
    );
  }

  // 构建图标
  Widget _buildIcon() {
    return Center(
      child: Icon(icon, size: size * 0.6, color: iconColor),
    );
  }

  // 加载失败图标
  Widget _buildErrorWidget(String message) {
    return Tooltip(
      message: message,
      child: Icon(Icons.error_outline, size: size / 3, color: Colors.red),
    );
  }

  // 静态资源路径处理
  Widget _buildLocalImage(String path) {
    final resolvedPath = kIsWeb
        ? path.startsWith('/')
            ? path
            : '/$path'
        : 'assets/${path.replaceFirst('assets/', '')}';

    return Image.asset(
      resolvedPath,
      width: size,
      height: size,
      fit: BoxFit.cover,
      errorBuilder: (_, __, ___) => _buildErrorWidget('资源未找到'),
    );
  }
}
